package net.vinote.smart.platform.module.database.bo;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;

import net.vinote.smart.platform.module.database.DBFactory;
import net.vinote.smart.platform.module.database.DBTransaction;
import net.vinote.smart.platform.module.database.DataBaseFeatureImp;
import net.vinote.smart.platform.module.log.RunLogger;

public class DBQuery {
	private static final RunLogger logger = RunLogger.getLogger();

	private Connection conn;

	private DBTransaction innerTx;

	private String querySql;

	private String[] fields;

	private String[] paramVal;

	// -----分页参数
	private int pageSize;// 页面大小

	private int pageNum;// 页面号

	public List<BizObject> getResultList() throws SQLException {
		initInnerTranstraction();
		querySql = DataBaseFeatureImp.getInstance().getPgination(querySql,
				pageSize, pageNum);
		StringBuffer sqlSB = new StringBuffer(querySql);
		PreparedStatement ps = conn.prepareStatement(querySql);
		if (paramVal != null) {
			sqlSB.append(" , param[");
			int length = paramVal.length;
			for (int i = 0; i < length; i++) {
				ps.setString(i + 1, paramVal[i]);
				sqlSB.append(i + 1).append(":").append(paramVal[i])
						.append(" ,");
			}
			sqlSB.append("]");
		}
		logger.log(Level.FINEST, sqlSB.toString());
		ResultSet rs = ps.executeQuery();
		List<BizObject> list = new ArrayList<BizObject>();
		while (rs.next()) {
			BizObject bo = new BizObject();
			for (int i = 0; i < fields.length; i++) {
				boolean index = fields[i].startsWith("O.")
						|| fields[i].startsWith("o.");
				String[] split = (index ? fields[i].substring(2) : fields[i])
						.split(" ");
				bo.setAttribute(split[split.length - 1], rs.getString(i + 1));
			}
			list.add(bo);
		}
		rs.close();
		rs = null;
		ps.close();
		ps = null;
		destoryInnerTranstraction();
		return list;
	}

	/**
	 * 查询指定字段
	 * 
	 * @return
	 * @throws SQLException
	 */
	public List<BizObject> getResultList(String... column) throws SQLException {
		querySql = DataBaseFeatureImp.getInstance().getColumnSQL(querySql,
				column);
		fields = column;
		return getResultList();
	}

	public void setFiledsSeq(String[] fields) {
		this.fields = fields;
	}

	public void setConnection(Connection conn) {
		this.conn = conn;
	}

	public BizObject getSingleResult() throws SQLException {
		List<BizObject> list = getResultList();
		return (list == null || list.size() == 0) ? null : list.get(0);
	}

	public BizObject getSingleResult(String... column) throws SQLException {
		List<BizObject> list = getResultList(column);
		return (list == null || list.size() == 0) ? null : list.get(0);
	}

	public void setQuerySql(String querySql) {
		this.querySql = querySql;
	}

	public String getQuerySql() {
		return querySql;
	}

	/***
	 * 在没有外部事务传入的情况下启动内部事务
	 */
	private void initInnerTranstraction() {
		if (conn == null) {
			innerTx = DBFactory.getFactory().getTransaction();
			conn = innerTx.getConn();
		}
	}

	/**
	 * 回收内部事务资源
	 * 
	 * @throws SQLException
	 */
	private void destoryInnerTranstraction() throws SQLException {
		if (innerTx != null) {
			innerTx.close();
			conn = null;
		}
	}

	public DBQuery setParamVal(String... paramVal) {
		this.paramVal = paramVal;
		return this;
	}

	/**
	 * 分页参数设置
	 */
	public DBQuery setPagination(int pageSize, int pageNum) {
		this.pageSize = pageSize;
		this.pageNum = pageNum;
		return this;
	}
}
